import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.budo.support.lang.util.ListUtil;

import lombok.Getter;
import lombok.Setter;

/**
 * @author limingwei
 */
@Getter
@Setter
public class WrapperType {
    private String _package;

    private String _src;

    private Set<Class<?>> _import = new HashSet<Class<?>>();

    public WrapperType(String _package, String _src) {
        this._package = _package;
        this._src = _src;
    }

    public void _import(Method method) {
        _import_0(method.getReturnType());

        for (Class<?> parameterTypes : method.getParameterTypes()) {
            _import_0(parameterTypes);
        }
    }

    public WrapperType _import_0(Class<?> type) {
        if (type.isArray()) {
            _import_0(type.getComponentType());
            return this;
        }

        if (type.isPrimitive()) {
            return this;
        }

        _import.add(type);
        return this;
    }

    public void append(String _src) {
        this._src += _src;
    }

    @Override
    public String toString() {
        String out = "package " + this._package + ";\n\n";

        List<Class<?>> sort = ListUtil.sort(this._import);
        for (Class<?> type : sort) {
            out += "import " + type.getName().replace("$", ".") + ";\n";
        }

        out += "\n";
        out += this._src;
        out += "}";
        return out;
    }
}